    dojo.require('dojo.parser');
    dojo.require('dojo.cookie');
	dojo.require("dojo.dnd.Source");
    dojo.require('dojo.data.ItemFileReadStore');
    dojo.require('dojox.grid.DataGrid');
	dojo.require('dojox.grid.Selection');
    dojo.require('dijit.form.Button');
    dojo.require('dijit.form.Button');
    dojo.require('dijit.ProgressBar');
    dojo.require('dijit.Dialog');

/*
 * to save the selections, need to have three bits of info in a cookie:
 * 
 * 1. selected funeral home
 * 2. selected funeral director
 * 3. selected case
 * 
 * to save the current selection state:
 * 
 * var selectedFH = getSelectedFhId();
 * var selectedFD = getSelectedFdId();
 * var selectedCase = getSelectedCaseId();
 * var cookieDough = selectedFH+':'+selectedFD+':'+selectedCase;
 * setCookie( 'VAS_selections', cookieDough);
 * 
 * to reload the selection state:
 * 
 * var cookieDough = getCookie('VAS_selections');
 * split them up by ':'
 * 
 * var elements = cookieDough.split(':');
 * 
 * setSelectedFHById( selectedFHid );
 * setSelectedFDById( selectedFDid );
 * setSelectedCaseById( selectedCaseId );
 * 
 */

	var cookieDough = dojo.cookie('VASksgridselections');
	if (cookieDough != null) 
	{
		console.log('cookie='+cookieDough);
		var nodes = cookieDough.split(':');
		if (nodes.length == 3) {
			if(nodes[0]=='') 
				selectedFHBranch = -1;
			else 
				selectedFHBranch = nodes[0];
			if(nodes[1]==-1) 
				selectedFDlicense = 'NO_LICENSE';
			else 
				selectedFDlicense = nodes[1];
			selectedCaseNum = nodes[2];
		}
		else {
			selectedFHBranch = -1;
			selectedFDlicense = 'NO_LICENSE';			
			selectedCaseNum = -1;
		}
	}
	else {
		selectedFHBranch = -1;
		selectedFDlicense = 'NO_LICENSE';			
		selectedCaseNum = -1;
	}
	
	// now, we can use the seletedFHBranch, selectedFDLicense, and selectedCaseNum
	// variables to figure out how to select the appropriate grid element.
	
	// this apparently has to be done in two steps - first, we have to look up the
	// FH, FD, and CASE items in each of the grids using the key values we have.
	// the result of those lookups will be items (JS objects) that we can then use
	// with grid.getItemIndex(item) to get back the index, which we can then use
	// to set the selected row in the grid.  Okay, it's three steps.
	
	if(selectedFHBranch != -1)
	{
		
	}
	
	if(selectedFDlicense != 'NO_LICENSE')
	{
		
	}
	
	if(selectedCaseNum != -1)
	{
		
	}
	
	var baseurl = '';
    var funeralDirsQueryBaseUrl = baseurl+'/index/ksfuneraldirectors/branch_number/';
    var funeralCasesQueryBaseUrl = baseurl+'/index/kscases/funeral_dir_id/';
    var funeralCaseReviewQueryBaseUrl = baseurl+'/index/reviewcase/case_id/';

    var funeralHomeReviewQueryBaseUrl = baseurl+'/index/funeralhome/branch_number/';
	var funeralDirReviewQueryBaseUrl = baseurl+'/index/funeraldirector/funeraldir_id/';
	
	// form of URL: /keystone/index/kscases/funeral_dir_id/LICENSE/branch_number/BRANCH
	
	var funeralhomeimportURL = '/index/funeralhomeimport/';
	var funeraldirsandcasesimportURL = '/index/funeralhomeimport/';
	
    var funeralDirsQueryUrl = funeralDirsQueryBaseUrl + selectedFHBranch;
    var funeralCasesQueryUrl = funeralCasesQueryBaseUrl + selectedFDlicense + '/branch_number/' + selectedFHBranch;

    var funeralHomeStore = new dojo.data.ItemFileReadStore({ url: baseurl+"/index/ksfuneralhomes/" });
    var funeralDirectorStore = new dojo.data.ItemFileReadStore({ url: funeralDirsQueryUrl });
    var funeralCasesStore = new dojo.data.ItemFileReadStore({ url: funeralCasesQueryUrl });

	function importNewFuneralHomes()
	{
		// 1. xhrGet() the importfuneralhomes action
	    dojo.xhrGet( {
	        url: funeralhomeimportURL,
	        handleAs: 'json',
	        load: function(results) 
			{
				// parse the results function.  for now, just echo out to console.log
				// if we had an error, pop an alert and boogie.
	        }
	    } );
		
		funeralHomesGrid.store.close();
		funeralHomesGrid.setStore(new dojo.data.ItemFileReadStore({ url: baseurl+"/index/ksfuneralhomes/" }));
		funeralHomesGrid._refresh();
	}
	
	function importArrangersAndCasesForBranch(branch)
	{		
		var fh_branch_number = getSelectedFuneralHomeBranchNumber();
		// 1. xhrGet() the importfuneralhomes action
	    dojo.xhrGet( {
	        url: funeraldirsandcasesimportURL+fh_branch_number,
	        handleAs: 'json',
	        load: function(results) 
			{
				// parse the results function.  for now, just echo out to console.log
				// if we had an error, pop an alert and boogie.
	        }
	    } );
		
		loadFuneralDirectorsForFH(fh_branch_number);
	}
	
    function loadFuneralDirectorsForFH( fh_id )
    {
	//FIXME - replace this with a numeric branch number
		var newFDstoreUrl = funeralDirsQueryBaseUrl + fh_id;
		console.log(newFDstoreUrl);
		funeralDirectorsGrid.store.close();
		delete funeralDirectorStore;
		var newFuneralDirectorStore = new dojo.data.ItemFileReadStore({ url: newFDstoreUrl });
		console.log('create new store');
		funeralDirectorsGrid.setStore(newFuneralDirectorStore);
		console.log('set store');
		funeralDirectorStore = newFuneralDirectorStore;
		console.log('about to refresh');
		funeralDirectorStore.fetch();
//		funeralDirectorsGrid.update();
		funeralDirectorsGrid._refresh();
		console.log('refreshed');
		selectedFHBranch = fh_id;
    }

    function loadCasesForFD( fd_id )
    {
		var newFuneralCasesQueryUrl = funeralCasesQueryBaseUrl + fd_id + '/branch_number/' + selectedFHBranch;
		var newFuneralCasesStore = new dojo.data.ItemFileReadStore({ url: newFuneralCasesQueryUrl });
		funeralCasesGrid.store = newFuneralCasesStore;
		funeralCasesGrid._refresh();
		delete funeralCasesStore;
		funeralCasesStore = newFuneralCasesStore;
    }

    function loadCasesForFDAtBranch( fd_id, branch )
    {
		var newFuneralCasesQueryUrl = funeralCasesQueryBaseUrl + fd_id + '/branch_number/' + branch;
		var newFuneralCasesStore = new dojo.data.ItemFileReadStore({ url: newFuneralCasesQueryUrl });
		funeralCasesGrid.store = newFuneralCasesStore;
		funeralCasesGrid._refresh();
		delete funeralCasesStore;
		funeralCasesStore = newFuneralCasesStore;
    }
	
	function saveGridSelectionState()
	{
		var selectedFHid = getSelectedFuneralHomeBranchNumber();
		var selectedFDid = getSelectedFuneralDirectorId();
		var selectedCaseid = getSelectedCaseId();
		
		var cookieDough = selectedFHid + ':' + selectedFDid + ':' + selectedCaseid;;

		console.log('cookie='+cookieDough);
		dojo.cookie('VASksgridselections', cookieDough);
	}
	
	function selectFHforId(fhid)
	{
		if (null == fhid) return; 
		console.log('selecting funeral home id = '+fhid);
				
		loadFuneralDirectorsForFH(fhid);
/*
	funeralHomesGrid.store.fetchItemByIdentity({
	  identity: fhid, 
	  onItem: function(item){
	  	// get index for this item and select it...
	  }
	});
	*/
	}	
	
	function selectFDforId(fdid)
	{
		if (null == fdid) return; 
		console.log('selecting funeral dir id = '+fdid);
		loadCasesForFD(fdid);
/*
		pantryStore.fetchItemByIdentity({
		  identity: "pepper", 
		  onItem: function(item){
		    console.debug("Pepper is in aisle ", pantryStore.getValue(item,"aisle"));
		  }
		});
 */	
	}
	
	function selectCaseForId(caseid)
	{
		if (null == caseid) return; 
		console.log('selecting case id = '+caseid);
/*
		pantryStore.fetchItemByIdentity({
		  identity: "pepper", 
		  onItem: function(item){
		    console.debug("Pepper is in aisle ", pantryStore.getValue(item,"aisle"));
		  }
		});
 */	
	}
	
    function getSelectedFuneralHomeName()
    {
		var items = funeralHomesGrid.selection.getSelected();
		if(items.length != 1) return -1;
	
		var selectedItem = items[0];
		var fhname = funeralHomesGrid.store.getValues(selectedItem, 'name');
	
		return fhname;
    }

    function getSelectedFuneralHomeBranchNumber()
    {
		var items = funeralHomesGrid.selection.getSelected();
		if(items.length != 1) return '';
	
		var selectedItem = items[0];

		var fhid = funeralHomesGrid.store.getValues(selectedItem, 'branch_number');
		return fhid;
    }

    function getSelectedFuneralHomeCityState()
    {
		var items = funeralHomesGrid.selection.getSelected();
		if(items.length != 1) return -1;
	
		var selectedItem = items[0];
		var fhcitystate = funeralHomesGrid.store.getValues(selectedItem, 'citystate');
	
		return fhcitystate;
    }

    function getSelectedFuneralDirectorName()
    {
		var items = funeralDirectorsGrid.selection.getSelected();
		if(items.length != 1) return -1;
	
		var selectedItem = items[0];
		var fdname = funeralDirectorsGrid.store.getValues(selectedItem, 'name');
	
		return fdname;
    }

// functions to enable/disable select buttons
    function disableFHselectButton()
    {
    }

    function enableFHselectButton()
    {
    }

    function disableFDselectButton()
    {
    }

    function enableFDselectButton()
    {
    }

// functions to grab IDs from grids.  these are needed to make the lists change when the [Select] buttons get clicked
// or we need to edit/review the data represented by a particular row

    function getSelectedFuneralDirectorId()
    {
		var items = funeralDirectorsGrid.selection.getSelected();
		if(items.length != 1) return -1;
	
		var selectedItem = items[0];
		var fdid = funeralDirectorsGrid.store.getValues(selectedItem, 'id');
	
		return fdid;
    }

    function getSelectedFuneralArrangerId()
    {
		var items = funeralDirectorsGrid.selection.getSelected();
		if(items.length != 1) return -1;
	
		var selectedItem = items[0];
		var fdid = funeralDirectorsGrid.store.getValues(selectedItem, 'arranger_id');
	
		return fdid;
    }

    function getSelectedCaseId()
    {
		var items = funeralCasesGrid.selection.getSelected();
		if(items.length != 1) return -1;
		var selectedItem = items[0];
		var casenum = funeralCasesGrid.store.getValues(selectedItem, 'case_num');
		return casenum;
    }

    function getSelectedVASCaseId()
    {
		var items = funeralCasesGrid.selection.getSelected();
		if(items.length != 1) return -1;
		var selectedItem = items[0];
		var casenum = funeralCasesGrid.store.getValues(selectedItem, 'id');
		return casenum;
    }

// functions called when "Select" button is clicked in the FD and Case lists, respectively
    function updateFuneralDirectorGrid( fh_id )
    {
	// set directors data store URL to use fh_id so we get back directors for funeral home fh_id
		console.log('getting funeral directors for funeral home '+fh_id);
    }

    function updateCaseGrid( fd_id )
    {
	// set cases data store URL to use fd_id so we get back directors for funeral dir fd_id
	console.log('getting cases for funeral home '+fd_id);
    }

// functions called to enable/disable Select and Edit buttons when there are/are not contents in the grids
    function enableFDButtons( yesNo )
    {
    }

    function enableCaseButtons( yesNo )
    {
    }

// this imports new FDs for the selected FH
    function fhGridImportBtnClick( )
    {
		var branch_number = getSelectedFuneralHomeBranchNumber();
		if(branch_number == null)
		{
			alert('no branch selected');
			return;
		}
		
		var name = getSelectedFuneralHomeName();
		console.log('getting new FDs for branch('+branch_number+'): ' + name);
		
		// sooo, in this one we call the function that does the dojo.xhrGet() to import
		// new FDs
		
		importDirectorsAtBranch( branch_number );
		
		// now close the directors grid store and reopen it
		loadFuneralDirectorsForFH(branch_number);
		funeralDirectorsGrid.selection.deselectAll();
		funeralDirectorsGrid.update();		
		loadCasesForFD('NO_LICENSE');
    }

	function selectBranch(branch_number)
	{
		loadFuneralDirectorsForFH(branch_number);
		funeralDirectorsGrid.selection.deselectAll();
		funeralDirectorsGrid.update();						
	}
	
	function selectArranger(fd_id)
	{
		loadCasesForFD(fd_id);
		funeralCasesGrid.selection.deselectAll();
	}
	
    function fhGridSelectBtnClick( )
    {
		var branch_number = getSelectedFuneralHomeBranchNumber();
		loadFuneralDirectorsForFH(branch_number);
		funeralDirectorsGrid.selection.deselectAll();
		funeralDirectorsGrid.update();		
		selectedFHBranch = branch_number;		
		loadCasesForFD('NO_LICENSE');
		var selFHname = getSelectedFuneralHomeName();
		document.getElementById('fhName').innerHTML = selFHname;
    }

    function fhGridReviewBtnClick( )
    {
		saveGridSelectionState();
		var branch_number = getSelectedFuneralHomeBranchNumber();
		var fh_url = funeralHomeReviewQueryBaseUrl + branch_number;
		window.location = fh_url;
    }

	// this imports new cases for the selected FD
    function fdGridImportBtnClick( )
    {
		var arranger_id = getSelectedFuneralArrangerId();
		
		if(arranger_id == null)
		{
			alert('no arranger selected');
			return;
		}
		
		var branch = getSelectedFuneralHomeBranchNumber();
		
		var name = getSelectedFuneralDirectorName();
		console.log('getting new cases for arranger('+arranger_id+'): ' + name);
		
//		#1 - computenewcases/arranger_id/<arranger_id>
		
		document.body.style.cursor = "wait";

		var newcases = getNewCasesForFD( arranger_id );
		console.log(newcases.length+' new cases found');

		var numnewcases = newcases.length;
		
//		#2 - foreach computed new case
//			#a - importnewcase/casenum/<casenumber>/arranger_id/<arranger_id>
		for( var i=0; i < newcases.length; i++ )
		{
			var vitals_id = newcases[i].vitalsid;
			var s = importNewCase( vitals_id, branch, arranger_id );
		}		
		document.body.style.cursor = "default";
		
		// now reload the cases grid for this arranger
		var fd_license = getSelectedFuneralDirectorId();
		loadCasesForFDAtBranch(fd_license,branch);
		funeralCasesGrid.selection.deselectAll();
    }

    function fdGridSelectBtnClick( )
    {
		var fd_id = getSelectedFuneralDirectorId();
		loadCasesForFD(fd_id);
		funeralCasesGrid.selection.deselectAll();
		var selFDname = getSelectedFuneralDirectorName();
		document.getElementById('fdName').innerHTML = selFDname;
    }

    function fdGridReviewBtnClick( )
    {
		saveGridSelectionState();
		var branch_number = getSelectedFuneralHomeBranchNumber();
		var fd_id = getSelectedFuneralDirectorId();
		var fd_url = funeralDirReviewQueryBaseUrl + fd_id + '/branch_number/' + branch_number;
		window.location = fd_url;
    }

// button click handler for Cases grid 'review' button

    function fdCaseReviewBtnClick( )
    {
		saveGridSelectionState();
		var case_id = getSelectedVASCaseId();
		var gotoURL = funeralCaseReviewQueryBaseUrl+case_id;
//		alert(gotoURL);
		window.location = gotoURL;
    }

    function merchEditBtnClick()
    {
		window.location = topMerchandiseBaseUrl;
    }

    function cashAdvanceBtnClick()
    {
		window.location = cashAdvanceEditBaseUrl;
    }

    function funeralHomeClicked(e)
	{
		var branch_number = getSelectedFuneralHomeBranchNumber();
		loadFuneralDirectorsForFH(branch_number);
		funeralDirectorsGrid.selection.deselectAll();
		funeralDirectorsGrid.update();
		
		selectedFHBranch = branch_number;
		
		loadCasesForFD('NO_LICENSE');
		var selFHname = getSelectedFuneralHomeName();
		document.getElementById('fhName').innerHTML = selFHname;
	}
	
    function funeralHomeDoubleClicked(e)
	{
		var branch_number = getSelectedFuneralHomeBranchNumber();
		var fh_url = funeralHomeReviewQueryBaseUrl + branch_number;
		window.location = fh_url;
	}
	
    function funeralDirectorClicked(e)
	{
		// hmmm.  change this to pick cases for FD at branch?
		var fd_id = getSelectedFuneralDirectorId();
		var branch_number = getSelectedFuneralHomeBranchNumber();
		loadCasesForFDAtBranch(fd_id,branch_number);
		funeralCasesGrid.selection.deselectAll();
		var selFDname = getSelectedFuneralDirectorName();
		document.getElementById('fdName').innerHTML = selFDname;
	}
	
    function funeralDirectorDoubleClicked(e)
	{
		var fd_id = getSelectedFuneralDirectorId();
		var fh_id = getSelectedFuneralHomeId();
		var fd_url = funeralDirReviewQueryBaseUrl + fd_id;
		window.location = fd_url;
	}
	
    function funeralCaseDoubleClicked(e)
	{
		var case_id = getSelectedVASCaseId();
		var gotoURL = funeralCaseReviewQueryBaseUrl+case_id;
//		alert(gotoURL);
		window.location = gotoURL;
	}

////////////////////////////////////////////////////////////////
// functions to import directors and cases
	
	function importDirectorsAtBranch( branch_number )	
	{
		document.body.style.cursor = "wait";
		console.log('importing directors at branch '+branch_number);
		// does xhrGet	
            dojo.xhrGet( {
                url:'/index/importnewdirectors/branch_number/'+branch_number,
                handleAs: 'json',
                load: function(main_results) 
					  {
					  	// what to do with the results?
						// mainly check the status value and
						// set the return value?
						// check main_results.status against "SUCCEEDED"
		              }
            } );
		document.body.style.cursor = "default";
	}

	function getNewCasesForFD( arranger_id )
	{
		document.body.style.cursor = "wait";
		var case_tuples = new Array();
        dojo.xhrGet( {
            url:'/index/computenewcases/arranger_id/'+arranger_id,
            handleAs: 'json',
			sync:true,
            load: function(main_results) 
				  {
					var v1 = main_results.newcasetuples;
					for( var i=0; i < v1.length; i++ )
					{
						var newtuple = {};
						var tuple = v1[i];
						console.log('casenum:'+tuple.casenum);
						console.log('vitalsid:'+tuple.vitalsid);
						console.log(' ');
						newtuple.casenum = tuple.casenum;
						newtuple.vitalsid = tuple.vitalsid;
						case_tuples[i] = newtuple;
					}
	              }
        } );
		console.log(case_tuples.length+' tuples');
		document.body.style.cursor = "default";
		return case_tuples;
	}
	
	function importNewCase( vitals_id, branch_number, arranger_id )
	{
		document.body.style.cursor = "wait";
		var url = '/index/importnewcase/vitals_id/'+vitals_id+
					'/arranger_id/'+arranger_id+
					'/branch_number/'+branch_number;
        dojo.xhrGet( {
            url:url,
            handleAs: 'json',
            load: function(output_msg) 
				  {
				  	// what to do with the results?
					console.log(output_msg.status);
	              }
        } );		
		document.body.style.cursor = "default";
	}
	
// serious Dojo begins here

    dojo.addOnLoad( function() {
	
	    funeralHomesGrid = new dojox.grid.DataGrid({
		query: { funeral_home_id: '*' },
		store: funeralHomeStore,
		structure: [
		    { field: "branch_number", name: "Branch#", width:"60px" },
		    { field: "branch_id", name: "BranchID", width:"60px" },
		    { field: "name", name: "Name", width:"auto" },
		    { field: "citystate", name: "City, State", width:"auto" }
		],
		rowsPerPage: 3,
		selectionMode: 'single'
		}, 'funeralHomesGridd');

	    funeralDirectorsGrid = new dojox.grid.DataGrid({
		query: { id: '*' },
		store: funeralDirectorStore,
		structure: [
		    { field: "id", name: "ID", width:"80px" },
		    { field: "arranger_id", name: "aID", hidden:"true" },
		    { field: "name", name: "Name", width:"auto" },
		    { field: "username", name: "VAS Username", width:"auto" }
		],
		rowsPerPage: 3,
		selectionMode: 'single'
		}, 'funeralDirectorsGridd');

	    funeralCasesGrid = new dojox.grid.DataGrid({
		query: { id: '*' },
		store: funeralCasesStore,
		structure: [
		    { field: "id", name: "Vitals ID", width:"auto" },
		    { field: "case_num", name: "FDMS Case Number", width:"auto" },
		    { field: "status", name: "Status", width:"auto" },
		    { field: "name", name: "Name", width:"auto" },
		    { field: "dob", name: "DOB", width:"auto" },
		    { field: "dod", name: "DOD", width:"auto" },
		    { field: "informant", name: "Informant", width:"auto" }
		],
		rowsPerPage: 3,
		selectionMode: 'single'
		}, 'funeralCasesGridd');

	 	dojo.connect( funeralHomesGrid, "onRowClick", funeralHomeClicked );
        dojo.connect( funeralHomesGrid, "onRowDblClick", funeralHomeDoubleClicked );
	 	dojo.connect( funeralDirectorsGrid, "onRowClick", funeralDirectorClicked );
        dojo.connect( funeralDirectorsGrid, "onRowDblClick", funeralDirectorDoubleClicked );
        dojo.connect( funeralCasesGrid, "onRowDblClick", funeralCaseDoubleClicked );

		funeralHomesGrid.startup();
		funeralDirectorsGrid.startup();
		funeralCasesGrid.startup();

	});
